package com.yxt.qmgf.klotski.ctrl;

import com.yxt.qmgf.klotski.service.GameService;
import com.yxt.qmgf.klotski.service.ScoreService;
import com.yxt.qmgf.klotski.vo.GameConfig;
import com.yxt.qmgf.klotski.vo.GameState;
import com.yxt.qmgf.klotski.vo.ScoreRecord;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;

public class klotskiController implements Initializable {
    private UserInfoVO vo;
    private GameService gameService;

    @FXML private GridPane gameGrid;
    @FXML private Label moveCountLabel;
    @FXML private Label messageLabel;
    @FXML private ComboBox<String> difficultyComboBox;
    private ScoreService scoreService = new ScoreService();

    private Stage gameStage; // 保存游戏窗口引用
    private GridPane currentGameGrid; // 当前游戏网格
    private int size = 3; // 默认3×3
    private int[][] board;
    private int emptyRow, emptyCol;
    private int moveCount = 0;

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
    }

    @FXML
    public void startGame() {
        System.out.println("开始游戏按钮被点击"); // 调试输出

        try {
            // 获取选择的难度
            String selected = difficultyComboBox.getSelectionModel().getSelectedItem();

            // 解析难度（兼容各种格式）
            size = Integer.parseInt(selected.replaceAll("[^0-9]", "").substring(0, 1));

            // 创建新窗口
            gameStage = new Stage();
            currentGameGrid = new GridPane();
            currentGameGrid.setHgap(5);
            currentGameGrid.setVgap(5);

            // 初始化游戏（在后台线程执行耗时操作）
            new Thread(() -> {
                initializeGame();

                // UI更新必须在JavaFX应用线程执行
                javafx.application.Platform.runLater(() -> {
                    Scene scene = new Scene(currentGameGrid);
                    scene.setOnKeyPressed(this::handleKeyPress);
                    gameStage.setScene(scene);
                    gameStage.setTitle("数字华容道 - " + selected);
                    gameStage.setOnCloseRequest(e -> {
                        gameStage = null;
                    });
                    gameStage.show();
                });
            }).start();

        } catch (Exception e) {
            System.err.println("启动游戏失败: " + e.getMessage());
            e.printStackTrace();
            showAlert("错误", "启动游戏失败", e.getMessage());
        }
    }

    private void initializeGame() {
        board = new int[size][size];
        currentGameGrid.getChildren().clear();
        moveCount = 0;

        // 初始化数字
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                board[i][j] = i * size + j + 1;
            }
        }

        // 设置空白格
        emptyRow = size - 1;
        emptyCol = size - 1;
        board[emptyRow][emptyCol] = 0;

        // 打乱顺序
        shuffleBoard();

        // 更新UI
        updateUI();
    }

    private void shuffleBoard() {
        System.out.println("开始打乱棋盘...");
        Random random = new Random();
        int shuffleCount = size * 10; // 减少打乱次数

        for (int i = 0; i < shuffleCount; i++) {
            int direction = random.nextInt(4);
            int newRow = emptyRow;
            int newCol = emptyCol;

            switch (direction) {
                case 0: newRow++; break; // 下
                case 1: newRow--; break; // 上
                case 2: newCol++; break; // 右
                case 3: newCol--; break; // 左
            }

            if (isValidMove(newRow, newCol)) {
                swapTiles(newRow, newCol, false);
            }

            // 每100次打乱让出CPU时间
            if (i % 100 == 0) Thread.yield();
        }
    }

    private void handleKeyPress(KeyEvent event) {
        int newRow = emptyRow;
        int newCol = emptyCol;

        switch (event.getCode()) {
            case UP: newRow++; break;
            case DOWN: newRow--; break;
            case LEFT: newCol++; break;
            case RIGHT: newCol--; break;
            default: return;
        }

        if (isValidMove(newRow, newCol)) {
            moveTile(newRow, newCol);
        }
    }

    private boolean isValidMove(int row, int col) {
        return row >= 0 && row < size && col >= 0 && col < size &&
                (Math.abs(row - emptyRow) + Math.abs(col - emptyCol) == 1);
    }

    private void moveTile(int row, int col) {
        swapTiles(row, col, true);

        // 检查是否完成
        if (isSolved()) {
            // 保存分数记录
            int gameSize = this.size; // 获取当前游戏难度
            scoreService.saveScore(vo, gameSize, moveCount);

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("恭喜");
            alert.setHeaderText("游戏完成");
            alert.setContentText(String.format("您用了 %d 步完成游戏！\n获得积分: %d",
                    moveCount,
                    scoreService.getUserScores(vo.getUsername()).get(0).getScore()));
            alert.showAndWait();
        }
    }

    private void swapTiles(int row, int col, boolean countMove) {
        // 交换方块
        board[emptyRow][emptyCol] = board[row][col];
        board[row][col] = 0;
        emptyRow = row;
        emptyCol = col;

        if (countMove) {
            moveCount++;
        }

        updateUI();
    }

    private void updateUI() {
        currentGameGrid.getChildren().clear();

        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (board[i][j] != 0) {
                    Rectangle tile = new Rectangle(80, 80);
                    tile.setFill(Color.LIGHTBLUE);
                    tile.setStroke(Color.BLACK);

                    Text text = new Text(String.valueOf(board[i][j]));
                    text.setFont(Font.font(20));

                    StackPane stackPane = new StackPane(tile, text);

                    final int row = i;
                    final int col = j;
                    stackPane.setOnMouseClicked(e -> moveTile(row, col));

                    currentGameGrid.add(stackPane, j, i);
                }
            }
        }
    }

    private boolean isSolved() {
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                int expected = (i == size-1 && j == size-1) ? 0 : i * size + j + 1;
                if (board[i][j] != expected) {
                    return false;
                }
            }
        }
        return true;
    }


    private void showAlert(String title, String header, String content) {
        javafx.application.Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle(title);
            alert.setHeaderText(header);
            alert.setContentText(content);
            alert.showAndWait();
        });
    }
    @FXML
    public void rule() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("游戏规则");
        alert.setHeaderText("数字华容道游戏规则");
        alert.setContentText("1. 使用鼠标点击或方向键移动方块\n" +
                "2. 目标是将数字按顺序排列\n" +
                "3. 空白格位于右下角时完成\n" +
                "4. 尽可能用最少的步数完成游戏");
        alert.showAndWait();
    }

    @FXML
    public void jifen() {
        List<ScoreRecord> userScores = scoreService.getUserScores(vo.getUsername());
        List<ScoreRecord> scoreboard = scoreService.getScoreboard();

        // 构建显示内容
        StringBuilder content = new StringBuilder();

        // 个人记录
        content.append("=== 您的游戏记录 ===\n");
        if (userScores.isEmpty()) {
            content.append("暂无游戏记录\n");
        } else {
            for (int i = 0; i < Math.min(userScores.size(), 5); i++) {
                ScoreRecord record = userScores.get(i);
                content.append(String.format("%d. %s - 步数: %d - 积分: %d (%s)\n",
                        i+1,
                        record.getDifficulty(),
                        record.getMoves(),
                        record.getScore(),
                        record.getFormattedTime()));
            }
        }

        // 排行榜
        content.append("\n=== 积分排行榜 ===\n");
        if (scoreboard.isEmpty()) {
            content.append("暂无排行榜数据\n");
        } else {
            for (int i = 0; i < Math.min(scoreboard.size(), 10); i++) {
                ScoreRecord record = scoreboard.get(i);
                content.append(String.format("%d. %s - %d分 (%s)\n",
                        i+1,
                        record.getUserName(),
                        record.getScore(),
                        record.getFormattedTime()));
            }
        }

        // 总积分
        int totalScore = userScores.stream().mapToInt(ScoreRecord::getScore).sum();
        content.append(String.format("\n您的总积分: %d", totalScore));

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("积分排行");
        alert.setHeaderText("积分排行榜");
        alert.setContentText(content.toString());

        // 设置对话框大小
        alert.getDialogPane().setMinHeight(400);
        alert.getDialogPane().setMinWidth(500);

        alert.showAndWait();
    }

    @FXML
    public void buy() {
        try {
            // 加载购买页面的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/Shop.fxml"));
            Parent root = loader.load();

            // 获取购买页面的控制器实例
            ShopController shopController = loader.getController();

            // 创建新的Stage并设置Scene
            Stage stage = new Stage();
            stage.setTitle("购买页面");
            stage.setScene(new Scene(root));
            // 如果需要模态展示，可添加以下代码
            stage.initModality(Modality.APPLICATION_MODAL);

            // 展示购买页面
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void back() {
        if (gameStage != null) {
            gameStage.close();
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 确保UI组件正确注入
        if (difficultyComboBox == null || gameGrid == null || moveCountLabel == null) {
            System.out.println("错误：FXML组件注入失败！");
            return;
        }

        // 初始化难度选择（使用中文乘号×）
        difficultyComboBox.getItems().addAll(
                "简单 (3×3)",
                "中等 (4×4)",
                "困难 (5×5)"
        );
        difficultyComboBox.getSelectionModel().selectFirst();
    }
}